import React, { useCallback, useEffect, useMemo, useState } from "react";
import WorkHeader from "./components/WorkHeader";
import WorkList from "./components/WorkList";
import ParallaxScrollView from "@/components/ParallaxScrollView";
import { PageParamsType, currentWorkListAtom, pageParamsAtom } from "@/store/work";
import { useAtom } from "jotai";
import { NativeScrollEvent, NativeSyntheticEvent, View } from "react-native";
import ResultShow from "../Home/ResultShow";
import { vw } from "@/common/dimensions";
import { useUpdateUserInfo } from "@/hooks/useUpdateUserInfo";
import { resultShowAtom } from "@/store/home";

export default function Work() {
    // 标记当前结果页是否为空
	const [currentWorkList, setCurrentWorkList] = useAtom<boolean>(currentWorkListAtom);
	// 页码
	const [pageParams, setPageParams] = useAtom<PageParamsType>(pageParamsAtom);
	// 添加 loading 状态
	const [nextPage, setNextPage] = useState(false);
	const [resultshow, setUseResultShow] = useAtom(resultShowAtom)
	const { updateUserInfo } = useUpdateUserInfo()
	const addPage = useCallback(() => {
        if(currentWorkList){
            changeNextPage()
            return
        }
		setPageParams((prev) => ({
			...prev,
			page: prev.page + 1,
		}));
	}, [setPageParams , currentWorkList]);

	const loadMoreData = useCallback(() => {
		if (nextPage) return;
		setNextPage(true);
		addPage();
		// 例如调用 API 请求来加载下一页的数据
	}, [addPage, nextPage]);

	const changeNextPage = () => {
        setNextPage(false)
	};

	const handleScroll = useCallback((event: NativeSyntheticEvent<NativeScrollEvent>) => {
        // 获取滚动高度和内容高度来判断是否到底部
        const { contentOffset, contentSize, layoutMeasurement } = event.nativeEvent;
        const isBottom = contentOffset.y + layoutMeasurement.height >= contentSize.height - 20; // 检查是否接近底部
        if (isBottom && !nextPage) {
            // 触发加载更多数据
            loadMoreData();
        }
    },[nextPage]);

	useEffect(()=>{
		updateUserInfo()
	},[])

	return (
		<ParallaxScrollView
			onScroll={handleScroll}
			headerBackgroundColor={{ light: "#D0D0D0", dark: "#353636" }}
			headerImage={<WorkHeader />}
		>
			{
				!!resultshow.length && (
					<View style={{paddingTop:4*vw , paddingHorizontal:4*vw , backgroundColor:"#fff"}}>
						<ResultShow />
					</View>
				)
			}
			<WorkList
				pageParams={pageParams}
                nextPage={nextPage}
				changeNextPage={changeNextPage}
			/>
		</ParallaxScrollView>
	);
}
